﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Fish.Models;
using Fish.DAL;
namespace Fish.Controllers
{
    /*Handles the creation of supplies, also allows guests to specify that they will bring some supply
     * with them.
     */
    [Authorize]
    public class SuppliesController : Controller
    {

        static int Aid = 1;
        static int Bid = 1;
        private FishContext db = new FishContext();

        // GET: /Supplies/
        public ActionResult Index(int? eventID)
        {
            System.Diagnostics.Debug.WriteLine("index: " + eventID);
            Events thisEvent = db.Events.Find(eventID);
            if (thisEvent != null)
            {

                Session["eventID"] = eventID;
                return View(thisEvent.Supplies.ToList());
            }
            else
            {
                return RedirectToAction("Index", "EventUserRelations");
            }

        }
        /*Checks the supply item that the user selected, decrements his amount from the total amount.
        Adds the user to the list of guests bringing this supply item. Also adds the task of bringing the supply item
         * to the users responsibilties list*/
        [HttpPost]
        public ActionResult IndexInput(string quantity, string supplyID)
        {

            int eventID = int.Parse(Session["eventID"].ToString());
            int userID = int.Parse(Session["userID"].ToString());
            Events thisEvent = db.Events.Find(eventID);
            int supId = int.Parse(supplyID);
            Supplies thisSupply = thisEvent.Supplies.Where(a=>a.ID ==supId).FirstOrDefault();
            Users thisUser = db.Users.Find(int.Parse(Session["userID"].ToString()));
            if (thisSupply.UserBringingID.Where(a=>a.UserBringingId ==thisUser.ID).Count()<1)
            {
                thisSupply.Users.Add(thisUser);
                System.Diagnostics.Debug.WriteLine("l = : " + thisSupply.Users.Count());
                MyInt myint = new MyInt();
                myint.ID = Aid;
                MyIntId myintId = new MyIntId();
                myintId.ID = Aid;
                Aid++;
                myint.UserBringingQuantity = int.Parse(quantity);
                myintId.UserBringingId = userID;
                myintId.UserBringingString = thisUser.Username;
                int originalQuantity = thisSupply.Quantity;
                thisSupply.UserBringingQuantity.Add(myint);
                thisSupply.UserBringingID.Add(myintId);
                thisSupply.Quantity = thisSupply.Quantity - int.Parse(quantity);
                if ((thisSupply.Quantity) <= 0)
                {
                    thisSupply.Quantity = 0;
                    myint.UserBringingQuantity = originalQuantity;
                }
                db.SaveChanges();
                EventUserRelations eur = db.EventUserRelations.Where(e => e.EventsID == thisEvent.ID && e.UsersID == userID).FirstOrDefault();

                string newTaskTxt = "Bring " + quantity + " of " + thisSupply.Name + " with you";
                MyTask newTask = new MyTask();
                newTask.ID = Bid;
                Bid++;
                newTask.taskMsg = newTaskTxt;
                newTask.ID = 1;
                eur.Tasks.Add(newTask);

                db.SaveChanges();
            }
            else
            {
                int index = -1;
                for (int i = 0; i < thisSupply.UserBringingID.Count(); i++)
                {
                    if (thisSupply.UserBringingID.ElementAt(i).UserBringingId == thisUser.ID)
                    {
                        index = i;
                        break;
                    }
                }

                        int originalQuantity = thisSupply.Quantity;
                        thisSupply.Quantity = thisSupply.Quantity - int.Parse(quantity);
                        if ((thisSupply.Quantity) <= 0)
                        {
                            thisSupply.UserBringingQuantity.ElementAt(index).UserBringingQuantity+= originalQuantity;
                            thisSupply.Quantity = 0;

                        }
                        else { 
                        thisSupply.UserBringingQuantity.ElementAt(index).UserBringingQuantity += int.Parse(quantity);
                        }
                        db.SaveChanges();
                        EventUserRelations eur = db.EventUserRelations.Where(e => e.EventsID == thisEvent.ID && e.UsersID == userID).FirstOrDefault();
                        MyTask newTask = new MyTask();
                        newTask.ID = Bid;
                        Bid++;
                        newTask.taskMsg = "Bring " + (thisSupply.UserBringingQuantity.ElementAt(index).UserBringingQuantity) + " of " + thisSupply.Name + " with you";
                        newTask.ID = 1;
                        eur.Tasks.Add(newTask);

                        db.SaveChanges();

            }

            return RedirectToAction("Index", new { eventID = int.Parse(Session["eventID"].ToString()) });

        }

        // GET: /Supplies/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return RedirectToAction("PageNotFound", "Error");

                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Supplies supplies = db.Supplies.Find(id);
            if (supplies == null)
            {
                return RedirectToAction("Expired", "Error");

                return HttpNotFound();
            }
            return View(supplies);
        }

        // GET: /Supplies/Create
        public ActionResult Create()
        {
            if (Session["eventID"] != null)
                return View();
            else
                return RedirectToAction("Expired", "Error");

        }

        // POST: /Supplies/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "ID,Name,Quantity")] Supplies supplies, string button)
        {
            if (ModelState.IsValid)
            {

                supplies.Users = new List<Users>();
                supplies.UserBringingQuantity = new List<MyInt>();
                supplies.UserBringingID = new List<MyIntId>();
                db.Supplies.Add(supplies);
                db.SaveChanges();

                Events thisEvent = db.Events.Find(int.Parse(Session["eventID"].ToString()));
                supplies.Event = thisEvent;
                thisEvent.Supplies.Add(supplies);
                db.SaveChanges();
                System.Diagnostics.Debug.WriteLine("ID = : " + supplies.ID);

                if (button.Equals("add"))
                {

                    return RedirectToAction("create");
                }

                if (button.Equals("finish"))
                {
                    return RedirectToAction("Index", new { eventID = int.Parse(Session["eventID"].ToString()) });
                }


            }
            else
            {
                if (button.Equals("finish"))
                {

                    return RedirectToAction("Index", new { eventID = int.Parse(Session["eventID"].ToString()) });
                }
            }

            return View(supplies);
        }

        // GET: /Supplies/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return RedirectToAction("PageNotFound", "Error");

                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Supplies supplies = db.Supplies.Find(id);
            if (supplies == null)
            {
                return RedirectToAction("Expired", "Error");

                return HttpNotFound();
            }
            return View(supplies);
        }

        // POST: /Supplies/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "ID,Name,Quantity")] Supplies supplies)
        {
            if (ModelState.IsValid)
            {
                db.Entry(supplies).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(supplies);
        }

        // GET: /Supplies/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Supplies supplies = db.Supplies.Find(id);
            if (supplies == null)
            {
                return HttpNotFound();
            }
            return View(supplies);
        }

        // POST: /Supplies/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Supplies supplies = db.Supplies.Find(id);
            db.Supplies.Remove(supplies);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
